#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/10/28 22:29
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : util_aliyun.py
# @Software: PyCharm
# @Desc    :
import json

from alibabacloud_dysmsapi20170525 import models as dysmsapi_models
from alibabacloud_dysmsapi20170525.client import Client as DysmsapiClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models


class AliYunSMS:
    """阿里云短信服务封装类（支持单发和批量发送）"""

    def __init__(self, sms_key, sms_secret):
        config = open_api_models.Config(
            access_key_id=sms_key,
            access_key_secret=sms_secret
        )
        config.endpoint = 'dysmsapi.aliyuncs.com'
        self.client = DysmsapiClient(config)

    def send_sms(self, mobile, sign_name, template_code, template_param, sms_up_extend_code='', out_id=''):
        """发送单条短信"""
        try:
            req = dysmsapi_models.SendSmsRequest(
                phone_numbers=mobile,
                sign_name=sign_name,
                template_code=template_code,
                template_param=json.dumps(template_param),
                sms_up_extend_code=sms_up_extend_code,
                out_id=out_id
            )

            runtime = util_models.RuntimeOptions()
            resp = self.client.send_sms_with_options(req, runtime)

            return {
                'success': resp.body.code == 'OK',
                'message': resp.body.message,
                'request_id': resp.body.request_id
            }
        except Exception as e:
            return {
                'success': False,
                'message': '发送短信异常: ' + str(e),
                'request_id': ''
            }

    def send_batch_sms(self, mobiles, sign_name, template_code, template_param, sms_up_extend_code='', out_id=''):
        """批量发送短信（相同内容）"""
        try:
            req = dysmsapi_models.SendBatchSmsRequest(
                phone_number_json=json.dumps(mobiles),
                sign_name_json=json.dumps([sign_name] * len(mobiles)),
                template_code=template_code,
                template_param_json=json.dumps([template_param] * len(mobiles)),
                sms_up_extend_code_json=json.dumps([sms_up_extend_code] * len(mobiles)),
                out_id=out_id
            )

            runtime = util_models.RuntimeOptions()
            resp = self.client.send_batch_sms_with_options(req, runtime)

            return {
                'success': resp.body.code == 'OK',
                'message': resp.body.message,
                'request_id': resp.body.request_id
            }
        except Exception as e:
            return {
                'success': False,
                'message': '批量发送短信异常: ' + str(e),
                'request_id': ''
            }


if __name__ == '__main__':
    # 初始化客户端（替换为你的实际AK/SK）
    sms = AliYunSMS(sms_key='LTAI5tQSwLqRCT6aMi7ghdkB',sms_secret='DvH2Ey5FDy8an9lJpbUbfbk20fmYbq')

    # 示例1：发送单条短信
    single_result = sms.send_sms(
        mobile='19045131668',
        sign_name='聪明掌柜',
        template_code='SMS_460755411',
        template_param={'code': '666666'}
    )
    print('单条发送结果:', single_result)
    # 单条发送结果: {'success': True, 'message': 'OK', 'request_id': '97460887-3CF9-522B-B3E1-7DAD913101B8'}
    # 单条发送结果: {'success': False, 'message': '触发分钟级流控Permits:1', 'request_id': '74E8BECE-2984-5D54-A557-8CEDD91D406A'}

    # # 示例2：批量发送短信（相同内容）
    # batch_result = sms.send_batch_sms(
    #     # mobiles=['19045131668', '19975080750'],  # 接收短信的手机号列表
    #     mobiles=['19045131668','19975080750'],  # 接收短信的手机号列表
    #     sign_name='聪明掌柜',
    #     template_code='SMS_460755411',
    #     template_param={'code': '111111'}
    # )
    # print('批量发送结果:', batch_result)
